import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import type { RootState } from "@/store";
import { message } from "antd";
type ColorStateType = {
  value: string;
  status: "idle" | "pending" | "fulfilled" | "rejected";
};

const initialState: ColorStateType = {
  value: "#fff",
  status: "idle",
};

const colorSlice = createSlice({
  name: "color",
  initialState,
  reducers: {},
  extraReducers(builder) {
    builder
      .addCase(getColorThunkCreator.pending, (state) => {
        state.status = "pending";
      })
      .addCase(
        getColorThunkCreator.fulfilled,
        (state, action: PayloadAction<string>) => {
          state.value = action.payload;
          state.status = "fulfilled";
        }
      ).addCase(getColorThunkCreator.rejected, (state, action) => {
        // #2
        state.status = 'rejected'
        state.value = 'red'
        message.error(action.error.message)
      })
  },
});

export default colorSlice.reducer;
export const selectColor = (state: RootState) => state.color.value;

const randomColor = (): Promise<string> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("#" + Math.random().toString(16).slice(2, 8));
    }, 1000);
  });
};

export const getColorThunkCreator = createAsyncThunk(
  "color/getcolor",
  async () => {
    try {
      const r = await randomColor();
      // #1
      // throw 'Error ~~~'
      return r;
    } catch (err) {
      return Promise.reject(err);
    }
  }
);

export const selectColorPending = (state: RootState) =>
  state.color.status === "pending";
